package com.ruoyi.ky450.service;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.constant.WebSocketConstant;
import com.ruoyi.ky450.vo.WebSocketVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint("/webSocket/{userId}")
@Component
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message){
        try {
            if (session != null) {
                synchronized (session) {
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //给指定用户发送信息
    public void sendInfo(String message) {
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
                log.info("主动发送|{}", message);
            } catch (Exception e) {
                log.error("sendInfo.error|", e);
            }
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        sessionPools.put(userId, session);
        addOnlineCount();
        log.info("{}加入webSocket！当前人数为{}", userId, onlineNum);
        WebSocketVo vo = new WebSocketVo(WebSocketConstant.TYPE_INIT,WebSocketConstant.RESULT_NO);
        try {
            vo = new WebSocketVo(WebSocketConstant.TYPE_INIT,WebSocketConstant.RESULT_OK);
        } catch (Exception e) {
            log.error("onOpen|", e);
        }
        sendMessage(session, JSON.toJSONString(vo));
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId) {
        sessionPools.remove(userId);
        subOnlineCount();
        log.info("{}断开webSocket连接！当前人数为{}", userId, onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) {
        log.info("收到|{}",message);
        WebSocketVo vo = JSON.parseObject(message,WebSocketVo.class);
        String data = WebSocketConstant.RESULT_OK;
        for (Session session : sessionPools.values()) {
            try {
                if(WebSocketConstant.TYPE_HEARTBEAT.equals(vo.getFlag())){
                    vo.setData(data);
                }
                sendMessage(session, JSON.toJSONString(vo));
                log.info("返回|{}",JSON.toJSONString(vo));
            } catch (Exception e) {
                log.error("onMessage.error|", e);
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Throwable throwable) {
        log.info("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}
